import React, { useContext, useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import {Table, Input, Button, Popconfirm, Form, Space, Switch, DatePicker, Select} from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import EditableTable from "../index";
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import axios from "../axios/axios";
import moment from "moment";
import {compareSortFunction} from "./index";

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

const EditableCell = ({
                          title,
                          editable,
                          children,
                          dataIndex,
                          record,
                          handleSave,
                          ...restProps
                      }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
        if (editing) {
            inputRef.current.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({
            [dataIndex]: record[dataIndex],
        });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{
                    margin: 0,
                }}
                name={dataIndex}
                rules={[
                    {
                        required: true,
                        message: `${title} is required.`,
                    },
                ]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{
                    paddingRight: 24,
                }}
                onClick={toggleEdit}
            >
                {children}
            </div>
        );
    }

    return <td {...restProps}>{childNode}</td>;
};

/*export function compareSortFunction(propeties) {
    var compareSort = (rowa, rowb) => sortFunction(rowa[propeties], rowb[propeties]);
    return compareSort;
}
export function sortFunction(a, b) {
    if (!a) {
        a = "";
    }
    if (!b) {
        b = "";
    }
    if ((typeof a) !== "number") {
        return a.localeCompare(b);
    }

}*/


const { RangePicker } = DatePicker;

function range(start, end) {
    const result = [];
    for (let i = start; i < end; i++) {
        result.push(i);
    }
    return result;
}

function disabledDate(current) {
    // Can not select days before today and today
    //return current && current < moment().endOf('day');
    return current && current <moment().subtract(1, "days"); //当天之前的不可选，不包括当天
}

function disabledDateTime() {
    let date = new Date();
    let hour=date.getHours();
    let mint=date.getMinutes();
    return {
        disabledHours: () => range(0,hour),
        disabledMinutes: () => range(0, mint+1),
        disabledSeconds: () => range(0, 60),
    };
}

function disabledRangeTime(_, type) {
    if (type === 'start') {
        return {
            disabledHours: () => range(0, 60).splice(4, 20),
            disabledMinutes: () => range(30, 60),
            disabledSeconds: () => [55, 56],
        };
    }
    return {
        disabledHours: () => range(0, 60).splice(20, 4),
        disabledMinutes: () => range(0, 31),
        disabledSeconds: () => [55, 56],
    };
}
const { Option } = Select;

export default class SearchResult extends React.Component {
    constructor(props) {
        super(props);
        this.columns = [
            {
                title: '标题',
                dataIndex: 'name',
                width: '10%',
                editable: true,
            },
            {
                title: '状态',
                dataIndex: 'state',
            },
            {
                title: '问卷类型',
                dataIndex: 'type',
            },
            {
                title: '创建时间',
                dataIndex: 'post',
                sorter: {
                    compare: (a, b) => new Date(a.post).getTime() - new Date(b.post).getTime(),
                },
                //两个排序方向
                sortDirections: ['descend', 'ascend'],
                //默认排序
                defaultSortOrder: 'descend',
            },
            {
                title: '发布时间',
                dataIndex: 'pdate',
                sorter: {
                    compare: compareSortFunction('pdate'),
                },
            },
            {
                title: '截止时间',
                dataIndex:'stoptime',
                render: (_, record) =>{
                    const temp=this.state.dataSource[record.key]&&this.state.dataSource[record.key].stprop;
                    const stop=this.state.dataSource[record.key]&&this.state.dataSource[record.key].stoptime;
                    const id=this.state.dataSource[record.key]&&this.state.dataSource[record.key].num;
                    const onChange=()=>{
                        let qid=this.state.dataSource[record.key]&&this.state.dataSource[record.key].num;
                        return(value, dateString)=>{
                            console.log(qid);
                            console.log(dateString);
                            axios.post('/ques/setValidTime ',{"qid" : qid,"valid_time":dateString}).then(
                                function (response){console.log("response:",response)}).catch(err=>console.log(err))
                        }
                    }
                    return(temp===1?<a>开启问卷后可设置</a>:
                            <DatePicker
                                format="YYYY-MM-DD HH:mm:ss"
                                disabledDate={disabledDate}
                                disabledTime={disabledDateTime}
                                //defaultValue={moment('12:08:23', 'HH:mm:ss')}
                                defaultValue={stop === undefined ?stop :moment(stop, 'YYYY-MM-DD HH:mm:ss')}
                                showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}

                                onChange={onChange()}


                            />
                    )
                }

            },
            {
                title: '回收量',
                dataIndex: 'ret',
                sorter: {
                    compare: (a, b) => a.ret - b.ret,
                },
            },
            {
                title: '操作(上方可选择其他操作)',
                dataIndex: 'op',
                render: (_, record) => {
                    const svalue=this.state.selectvalue;
                    //return(svalue)
                    if(svalue==0){
                        return(
                            <Space size="middle">
                                <a onClick={() => this.handleRelook(record.key)}>预览</a>
                            </Space>
                        )
                    }
                    else if(svalue==1){
                        return (
                            <Space size="middle">
                                <a onClick={() => this.handleEdit(record.key)
                                }>编辑</a>
                            </Space>
                        )
                    }
                    else if(svalue==2){
                        return (
                            <Space size="middle">
                                <a onClick={() => this.handleCopy(record.key)
                                }>复制</a>
                            </Space>
                        )
                    }
                    else if(svalue==3){
                        return (
                            <Space size="middle">
                                <a onClick={() => this.handleData(record.key)
                                }>数据分析</a>
                            </Space>
                        )
                    }
                    else if(svalue==4){
                        return(this.state.dataSource.length >= 1 ? (
                                <Popconfirm title="确认删除?" onConfirm={() => this.handleDelete(record.key)}>
                                    <a>删除</a>
                                </Popconfirm>
                            ) : null
                        )
                    }
                    else if(svalue==5){
                        return (
                            <Space size="middle">
                                <a onClick={() => this.handleLJ(record.key)
                                }>查看链接</a>
                            </Space>
                        )
                    }

                }
            },
            /*{
                title: '预览',
                dataIndex: 're',
                render: (_, record) => (
                    <Space size="middle">
                        <a onClick={() => this.handleRelook(record.key)}>预览</a>
                    </Space>
                ),
            },
            {
                title: '编辑',
                dataIndex: 'edt',
                render: (_, record) => (
                    <Space size="middle">
                        <a onClick={() => this.handleEdit(record.key)}>编辑</a>
                    </Space>
                ),
            },
            {
                title: '复制',
                dataIndex: 'copy',
                render: (_, record) => (
                    <Space size="middle">
                        <a onClick={() => this.handleCopy(record.key)
                        }>复制</a>
                    </Space>
                ),
            },
            {
                title: '数据',
                dataIndex: 'analys',
                render: (_, record) => (
                    <Space size="middle">
                        <a onClick={() => this.handleData(record.key)
                        }>分析</a>
                    </Space>
                ),
            },
            {
                title: '删除',
                dataIndex: 'operation',
                render: (_, record) =>
                    this.state.dataSource.length >= 1 ? (
                        <Popconfirm title="确认删除?" onConfirm={() => this.handleDelete(record.key)}>
                            <a>删除</a>
                        </Popconfirm>
                    ) : null,
            },*/
            {
                title: '开启/关闭',
                dataIndex: 'openclose',
                render: (_, record) => {
                    const tmp=this.state.dataSource[record.key]&&this.state.dataSource[record.key].stprop;
                    return(<Switch
                        checkedChildren="开启"
                        unCheckedChildren="关闭"
                        checked={(tmp===1)?false:true}
                        onChange={() => this.handleOC(record.key)}
                    />)
                },
            },
        ];
        this.state = {
            dataSource: [
                /*{
                    key: 0,
                    name: 'aa',
                    num:1,
                    state: '进行中',
                    post: '2021-06-02',
                    ret: '100'
                },
                {
                    key: 1,
                    name: 'bb',
                    num:2,
                    state: '进行中',
                    post: '2021-05-09',
                    ret: '200'
                },*/
            ],
            count: 0,
            selectvalue:0
        };

    }

    componentWillMount() {
        const _this=this;
        const changeDate=(value)=>{
            return moment(value).format('YYYY-MM-DD HH:mm:ss');
        }
        const getState=(state)=>{
            if(state===1){
                return '未开启'
            }
            else if(state===2){
                return '进行中'
            }
        }
        axios.get('/ques/searchQuesByKeyWord', {params: {keyword:this.props.location.state.keyword}})
            .then(function (response) {
                console.log(response.data.data)

                let arr=response.data.data
                for(var i=0;i<arr.length;i++){
                    const { count,dataSource } = _this.state;
                    const newData ={
                        key:count,
                        name: arr[i].title,
                        num: arr[i].q_id,
                        state: getState(arr[i].state),
                        post: changeDate(arr[i].create_time),
                        pdate:changeDate(arr[i].release_time),
                        ret: arr[i].recover_num,
                        stprop:arr[i].state,
                        stoptime:changeDate(arr[i].valid_time),
                        type:arr[i].q_type
                    }
                    _this.setState({
                        dataSource: [...dataSource, newData],
                        count: count + 1,
                    })
                }

            })
    }


    getTodayDate=()=> {
        var date = new Date();
        return moment(date).format('YYYY-MM-DD HH:mm:ss');
    };
    handleCopy= (key) => {
        let tmp = this.state.dataSource[key] && this.state.dataSource[key].num;
        let title = this.state.dataSource[key] && this.state.dataSource[key].name;
        const _this=this;
        const getState=(state)=>{
            if(state===1){
                return '未开启'
            }
            else if(state===2){
                return '进行中'
            }
        }
        const { dataSource } = this.state;
        const dataSource2 = [...this.state.dataSource];
        alert("复制成功，已生成副本");
        axios.post('/ques/copyQues', {"qid": tmp}).then(
            function (response) {
                console.log("response:", response);
                let arr=response.data.data;
                const newData = {
                    key: dataSource2.length,
                    name:  arr.title,
                    num: arr.num,
                    state: getState(arr.state),
                    post: arr.create_time,
                    ret: arr.total,
                    stprop: arr.state,
                    type: arr.type,
                }
                _this.setState({
                    dataSource: [...dataSource, newData],
                });
            }).catch(err => console.log(err))
        console.log(dataSource)
    }


    handleOC= (key) =>{
        let value=this.state.dataSource[key]&&this.state.dataSource[key].state;
        const chk=this.state.dataSource[key]&&this.state.dataSource[key].stprop;
        let tmp=this.state.dataSource[key]&&this.state.dataSource[key].num;
        let time=this.state.dataSource[key]&&this.state.dataSource[key].pdate;
        const change=(pro)=>{
            if(pro===2){
                return 1;
            }
            else if(pro===1){
                return 2;
            }
        }
        const getState=(state)=>{
            if(state===1){
                return '未开启'
            }
            else if(state===2){
                return '进行中'
            }
        }
        const opendate=(pro,val)=>{
            if(pro===1){
                return val;
            }
            else if(pro===2){
                return this.getTodayDate();
            }
        }
        if(chk===1){
            alert("访问链接：http:localhost:3000/fill"+tmp);
        }
        const { dataSource } = this.state;
        this.setState({
            dataSource:dataSource.map((item,idx)=>
                key===idx?{...item,stprop:change(chk),state:getState(change(chk)),pdate:opendate(change(chk),time)}:item,
            )
        })
        axios.post('/ques/setState',{"qid" : tmp,"state":change(chk)}).then(
            function (response){console.log("response:",response)}).catch(err=>console.log(err))
    }

    handleRelook= (key) =>{
        let value=this.state.dataSource[key]&&this.state.dataSource[key].num;
        this.props.history.push({pathname:"/preview/", state :value});
    }

    handleEdit= (key) =>{
        let value=this.state.dataSource[key]&&this.state.dataSource[key].num;
        let type=this.state.dataSource[key]&&this.state.dataSource[key].type;
        let tmp=this.state.dataSource[key]&&this.state.dataSource[key].stprop;
        if(tmp===2){
            alert("请先关闭问卷")
        }
        else if(tmp===1){
            if(type==="普通问卷") {
                this.props.history.push({pathname: "/edit/", state: value});
            }
            else if(type==="投票问卷"){
                this.props.history.push({pathname: "/vote/", state: value});
            }
            else if(type==="报名问卷"){
                this.props.history.push({pathname: "/apply/", state: value});
            }
            else if(type==="考试问卷"){
                this.props.history.push({pathname: "/test/", state: value});
            }
            else if(type==="打卡问卷"){
                this.props.history.push({pathname: "/epidemic/", state: value});
            }
        }
    }
    handleData= (key) =>{
        let value=this.state.dataSource[key]&&this.state.dataSource[key].num;
        this.props.history.push({pathname:"/content/", state :value});
    }
    handleLJ= (key) =>{
        let tmp=this.state.dataSource[key]&&this.state.dataSource[key].stprop;
        const stat=this.state.dataSource[key]&&this.state.dataSource[key].stprop;
        if(stat===2){
            alert("访问链接：http:localhost:3000/fill"+tmp);
        }
        else if(stat===1){
            alert("请先开启问卷")
        }
    }

    handleOptionChange=(value)=>{
        //const _this=this;
        console.log(value)
        this.setState({
            selectvalue: value
        });
    }


    handleDelete = (key) => {
        const dataSource = [...this.state.dataSource];
        let value=this.state.dataSource[key]&&this.state.dataSource[key].num;
        let tmp=this.state.dataSource[key]&&this.state.dataSource[key].stprop;
        console.log(value);
        console.log(tmp);
        console.log(this.state.dataSource[key])

        axios.post('/ques/delQues',{"qid" : value}).then(
            function (response){console.log("response:",response)}).catch(err=>console.log(err))


        dataSource.splice(key,1)
        for(var i=0;i<dataSource.length;i++){
            dataSource[i].key=i;
        }
        this.setState({
            dataSource:dataSource
        })

    };
    render() {
        const { dataSource } = this.state;
        const components = {
            body: {
                row: EditableRow,
                cell: EditableCell,
            },
        };
        const columns = this.columns.map((col) => {
            if (!col.editable) {
                return col;
            }

            return {
                ...col,
                onCell: (record) => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                }),
            };
        });
        return (
            <div>
                <Link to="/home">
                    <Button
                        type="primary"
                        style={{
                            marginBottom: 16,
                            marginTop:10
                        }}
                        onClick={this.handleback}
                    >
                        返回
                    </Button>
                </Link>
                <br />
                <Select
                    onChange={this.handleOptionChange}
                    showSearch
                    style={{ width: 300 ,float: 'right',marginBottom: 30,marginTop:20}}
                    placeholder="请选择操作"
                    optionFilterProp="children"
                    filterOption={(input, option) =>
                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                >
                    <Option value="0">预览</Option>
                    <Option value="1">编辑</Option>
                    <Option value="2">复制</Option>
                    <Option value="3">查看数据分析</Option>
                    <Option value="4">删除</Option>
                    <Option value="5">查看问卷链接</Option>
                </Select>
                <br />
                <Table
                    components={components}
                    rowClassName={() => 'editable-row'}
                    bordered
                    dataSource={dataSource}
                    columns={columns}
                />
            </div>

        );
    }
}